package com.example.sqlite;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private SimpleAdapter simpleAdapter;
    private ListView listview;
    public DBOpenHelper db;
    private List<Map<String, Object>> data = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listview = findViewById(R.id.list);
        String[] from = {"id", "class", "number", "name"};
        int[] to = {R.id.tv_id1, R.id.tv_class1, R.id.tv_number1, R.id.tv_name1};
        db = new DBOpenHelper(this, 1);
        db.insert(new Student("李宇航", "数字媒体171", "202170425", 1));
        simpleAdapter = new SimpleAdapter(this, data, R.layout.list_item, from, to);
        listview.setAdapter(simpleAdapter);
        refresh();
        findViewById(R.id.add_stu).setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, AddActivity.class);
            startActivityForResult(intent,1);
        });
    }

    void refresh() {
        data.clear();
        Student[] students = db.queryAllData();
        if (students == null) {
            return;
        }
        String cl;
        String num;
        String na;
        int id;
        for (Student student : students) {
            cl = student.getClas();
            num = student.getNumber();
            na = student.getName();
            id = student.getID();
            //Toast.makeText(MainActivity.this,cl+num+na,Toast.LENGTH_SHORT).show();
            Map<String, Object> item = new HashMap<>();
            item.put("id", id);
            item.put("class", cl);
            item.put("number", num);
            item.put("name", na);
            data.add(item);
        }
        simpleAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        refresh();
    }
}